<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>完成动态表格</title>
    <style>
        #table2 {
            background-color: black;

            height: 300px;
            width: 300px;

            cellspacing: 1px;
        }
    </style>
</head>

<body style="height: 800px">

<script>
    var table = document.createElement("table");
    table.id = "table2";
    table.align = "center";

    // table.cellSpacing="1px";
    //  var cellspacing = document.createTextNode("cellspacing");
    //
    //  cellspacing.nodeValue="1px";
    // table.setAttributeNode(cellspacing);
    var caption = document.createElement("caption");
    caption.innerText = "学习表";
    table.appendChild(caption)
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(table);
    for (let i = 0; i < 5; i++) {
        var tr = document.createElement("tr");
        tr.bgColor = "white";
        tr.setAttribute("align", "center");
        for (let j = 0; j < 4; j++) {
            if (i == 0) {
                var td = document.createElement("th");
                td.innerText = "第" + (j + 1) + "行";
            } else {
                var td = document.createElement("td");
                td.innerText = i + "." + j;
            }
            //鼠标按下事件
            td.onmousedown = function () {
                /*问题在于您在所有单元格中重复使用了同一个变量  td ，
                这导致最后分配的事件处理程序覆盖了之前的事件。
                为了解决这个问题，您可以为每个单元格创建一个单独的函数来处理事件。*/
                this.style.height = "90px";
                this.style.width = "90px";
            }
//鼠标移动到元素上事件
            td.onmouseenter = function () {
                //设备背景颜色为红色
                this.style.background = "red";
            }
            //鼠标离开事件
            td.onmouseleave = function () {
                this.style.height = "57.91px";
                this.style.width = "72.84px";
                this.style.background = ""
            }
            tr.appendChild(td);
        }

        var input = document.createElement("input");

        input.type = "button"
        input.value = "删除第" + (i + 1) + "行";

        var deleteCell = document.createElement("td");
        deleteCell.appendChild(input);
        tr.appendChild(deleteCell);
       input.onclick = function () {
            table.deleteRow(i);
        }

       //  (function (row) {
       //      input.onclick = function () {
       //          row.remove();
       //      }
       //  })(tr);
       //  table.appendChild(tr);
    }

</script>
</body>
</html>